﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace GiMessCommons
{
    public static class NetUtils
    {
        #region Utils

        public static int stringToInt(string s)
        {
            int ret = 0;
            char[] chrs = s.ToCharArray();
            for (int i = 0; i < chrs.Length; i++)
            {
                ret = ret * 256 + (int)chrs[i];
            }
            return ret;
        }

        public static string intToString(int number)
        {
            byte a, b, c, d; // number = abcd
            string ret;

            d = (byte)(number % 256);
            number = number / 256;
            c = (byte)(number % 256);
            number = number / 256;
            b = (byte)(number % 256);
            number = number / 256;
            a = (byte)(number % 256);

            ret = new string(new char[] { (char)a, (char)b, (char)c, (char)d });

            return ret;
        }

        public static string EncodePassword(string originalPassword)
        {
            byte[] originalBytes;
            byte[] encodedBytes;

            MD5 md5;
            StringBuilder sb;
            
            md5 = new MD5CryptoServiceProvider();
            sb  = new StringBuilder(32);

            originalBytes = Encoding.UTF8.GetBytes(originalPassword);
            encodedBytes  = md5.ComputeHash(originalBytes);

            for (int i = 0; i < encodedBytes.Length; i++)
            {
                sb.Append(encodedBytes[i].ToString("x2"));
            }

            return sb.ToString();
        }

        #endregion
    }
}
